# _*_ coding utf-8 _*_
# FILENAME：.py
# DESCRIPTION: 基础Model
# AUTH: ZB
# DATE: 2022/6/2 10:00 下午
import datetime
import urllib.parse

from sqlalchemy import create_engine, Column, Integer, DATETIME, func
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# 初始化数据库连接:
from constant import DB_CON_URI
from utils.confUtils import read_db_config

engine = create_engine(
    DB_CON_URI,
    encoding="utf-8",
    # echo=True,
    pool_recycle=3600,
    pool_pre_ping=True
)
# 创建对象的基类:
Base = declarative_base()


# 初始化数据库
def init_db():
    Base.metadata.create_all(engine)


# 获取session
def get_session():
    db_session = sessionmaker(bind=engine)
    return db_session()


## 基础model
class BaseModel(Base):

    __abstract__ = True

    # 表的结构:
    id = Column(Integer, primary_key=True, autoincrement=True, comment='ID')
    create_date = Column(DATETIME, server_default=func.now(), nullable=False, comment='创建时间')
    update_date = Column(DATETIME, server_default=func.now(), onupdate=func.now(), nullable=False, comment='更新时间')
    is_del = Column(Integer, default=0, nullable=False, comment='状态，1删除；0未删除')


# 单表删除数据
def delete(model):
    # 当前时间
    time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    # 获取dbsession
    session = get_session()
    # 赋值变更时间
    model.update_date = time
    # 更新
    session.query(type(model)).filter(type(model).id == model.id).update({'is_del': 1})
    # 提交&关闭
    session.commit()
    session.close()
